package com.tyj.tuyijieapp.config.security.captcha;

import cn.hutool.core.util.StrUtil;
import com.tyj.tuyijiesystem.model.juser.service.auth.AuthServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 * 验证码登录
 * </p>
 *
 * @author lhf
 * @since 2020/6/6
 */
@Component
public class CaptchaProvider implements AuthenticationProvider {

    private static Logger log = LoggerFactory.getLogger(CaptchaProvider.class);

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private AuthServiceImpl userService;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = authentication.getName();
        String code = (String) authentication.getCredentials();
        log.debug("验证码登录");
        UserDetails user = userService.loadUserByUsername(phone);
        if (user == null) {
            throw new UsernameNotFoundException("用户未找到");
        }

        String login_code = redisTemplate.opsForValue().get("login:code:" + phone);
        if (StrUtil.isEmpty(login_code)) {
            throw new BadCredentialsException("验证码已过期");
        }
        if (!StrUtil.equals(login_code, code)) {
            throw new BadCredentialsException("验证码验证码不正确");
        }
        CaptchaProviderToken captchaProviderToken = new CaptchaProviderToken(user, authentication.getCredentials());
        captchaProviderToken.setDetails(authentication.getDetails());
        return captchaProviderToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CaptchaProviderToken.class.isAssignableFrom(authentication);
    }

}
